const activityDOM = document.getElementById('activity')
const mainDOM = document.getElementById('main')

const importDOM = document.getElementById('import')
const exportDOM = document.getElementById('export')
const copyDOM = document.getElementById('copy')

/**
 * 原图dom
 */
const srcDOM = document.getElementById('src')

/**
 * 输出dom
 */
const pixelDOM = document.getElementById("pixel")
const pixelCtx = pixelDOM.getContext('2d')

/**
 * 像素化dom
 */
const canvasDOM = document.getElementById('canvas')
const canvasCtx = canvasDOM.getContext('2d')

const precisionDOM = document.getElementById('precision')

/**
 * 精度
 */
var precision = 50

const clientWidth = 320

var outputFileName
var outputDataURL

activityDOM.addEventListener('click', () => {
	upload()
})

importDOM.addEventListener('click', () => {
	upload()
})

exportDOM.addEventListener('click', () => {
	window.preload.downloadFile(outputDataURL, outputFileName)
		.then(e => {
			utools.showNotification('导出成功')
		})
})

copyDOM.addEventListener('click', () => {
	utools.hideMainWindowPasteImage(outputDataURL)

	utools.showNotification('复制成功')
})

precisionDOM.addEventListener('change', (e) => {
	precision = e.target.value

	toPixel()

	return true
})

const upload = function() {
	window.preload.openFile({
		title: '请选择一张图片',
		buttonLabel: '选择',
		filters: [{
			name: '图片',
			extensions: ['jpg', 'jpeg', 'png', 'webp']
		}]
	}).then(async file => {

		await input(file)

		toPixel()

		activityDOM.style.display = 'none'
		mainDOM.style.display = 'block'
	}).catch(e => {
		console.error("打开文件失败", e);
	})
}

const input = async function(file) {
	const [promise, onResolve, onReject] = createPromise()

	const img = await readFile(file)

	await loadImage(img)

	const scale = clientWidth / srcDOM.naturalWidth

	//拉伸原图
	srcDOM.width = srcDOM.naturalWidth * scale
	srcDOM.height = srcDOM.naturalHeight * scale

	pixelDOM.width = srcDOM.width
	pixelDOM.height = srcDOM.height

	pixelCtx.imageSmoothingEnabled =
		pixelCtx.mozImageSmoothingEnabled =
		pixelCtx.webkitImageSmoothingEnabled =
		pixelCtx.msImageSmoothingEnabled = false

	outputFileName = 'pixel_' + file.name.split('.')[0] + '.png'

	onResolve()

	return promise
}

const toPixel = async function() {
	//通过canvas缩小原图
	canvasDOM.width = precision * srcDOM.width / 100
	canvasDOM.height = precision * srcDOM.height / 100

	canvasCtx.clearRect(0, 0, canvasDOM.width, canvasDOM.height)
	canvasCtx.drawImage(srcDOM, 0, 0, canvasDOM.width, canvasDOM.height)

	//将缩小后的原图画在输出canvas上
	pixelCtx.clearRect(0, 0, pixelDOM.width, pixelDOM.height)
	pixelCtx.drawImage(canvasDOM, 0, 0, pixelDOM.width, pixelDOM.height)

	outputDataURL = pixelDOM.toDataURL('image/png', 1)
}

const readFile = function(file) {
	const [promise, onResolve, onReject] = createPromise()

	const fileReader = new FileReader()

	fileReader.addEventListener('loadend', async e => {
		if (e.target?.result) {
			onResolve(e.target.result)
		} else {
			onReject()
		}
	})

	fileReader.readAsDataURL(file)

	return promise
}

const loadImage = function(fileUrl) {
	const [promise, onResolve, onReject] = createPromise()

	srcDOM.onload = () => {
		onResolve()
	}

	srcDOM.src = fileUrl

	return promise
}

const createPromise = function() {
	var onResolve, onReject
	const promise = new Promise((resolve, reject) => {
		onResolve = resolve
		onReject = reject
	})

	return [promise, onResolve, onReject]
}